import React, { useEffect } from "react";
import axios from "../../../http/index";
import moment from "moment";
import {
  Form,
  Input,
  Button,
  Table,
  Tag,
  Space,
  DatePicker,
  Modal,
  Image,
  Popconfirm,
  message
} from "antd";
import { useState } from "react";
import {
  BrowserRouter as Router,
  Switch,
  Route,
  Link,
  Redirect,
} from "react-router-dom";
import TitelSmall from "../../../components/TitleSmall/TitelSmall";
import { SearchOutlined } from "@ant-design/icons";
import "./index.scss";
import user from "./images/user.png";
import money from "./images/money.png";
import foot from "./images/foot.png";

export default function UserList() {
  const { TextArea } = Input;
  const [inval, setsetSMScontent] = useState("");
  const [invalTitle, setInvalTitle] = useState("");
  const [state, setState] = useState({
    selectedRowKeys: [],
  });
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [isModalGroup, setIsModalGroup] = useState(false);
  const [isModalCoupon, setIsModalCoupon] = useState(false);
  const [isModalList, setIsModalList] = useState(false);
  const [excelData, setexcelData] = useState([]);
  const [headdata, setHeaddata] = useState([]);
  const { RangePicker } = DatePicker;

  const columns = [
    {
      title: "用户ID",
      dataIndex: "id",
      key: "id",
    },
    {
      title: "用户昵称",
      dataIndex: "nickname",
      key: "nickname",
    },
    {
      title: "用户账号",
      dataIndex: "account",
      key: "account",
    },
    {
      title: "会员等级",
      dataIndex: "viplv",
      key: "viplv",
      render: (text, record) => {
        let span = "";
        if (record.viplv == 1) {
          span = <span style={{ color: "#343434" }}>普通会员</span>;
        } else if (record.viplv == 2) {
          span = <span style={{ color: "green" }}>黄金会员</span>;
        } else if (record.viplv == 3) {
          span = <span style={{ color: "blue" }}>白金会员</span>;
        } else if (record.viplv == 4) {
          span = <span style={{ color: "red" }}>钻石会员</span>;
        }
        return <div>{span}</div>;
      },
    },
    {
      title: "认证状态",
      key: "attestation_status",
      dataIndex: "attestation_status",
      render: (text, record) => {
        let span = "";
        switch (record.attestation_status) {
          case 1:
            return (span = <span style={{ color: "red" }}>未认证</span>);
          case 2:
            return (span = <span style={{ color: "green" }}>已认证</span>);
          case 3:
            return (span = <span style={{ color: "blue" }}>认证中</span>);
          default:
            return <div>{span}</div>;
        }
      },
    },
    {
      title: "贷款总额",
      dataIndex: "loan_amount",
      key: "loan_amount",
    },
    {
      title: "订单数量",
      dataIndex: "s1",
      key: "s1",
    },
    {
      title: "逾期金额",
      dataIndex: "s2",
      key: "s2",
    },
    {
      title: "黑白名单",
      key: "credit_blank",
      dataIndex: "credit_blank",
      render: (text, record) => {
        let span = "";
        switch (record.credit_blank) {
          case 1:
            return (span = <span style={{ color: "grey" }}>白</span>);
          case 2:
            return (span = <span style={{ color: "black" }}>黑</span>);
          default:
            return <div>{span}</div>;
        }
      },
    },
    {
      title: "账户状态",
      key: "account_status",
      dataIndex: "account_status",
      render: (text, record) => {
        let span = "";
        switch (record.account_status) {
          case 1:
            return (span = <span style={{ color: "blue" }}>正常</span>);
          case 2:
            return (span = <span style={{ color: "green" }}>冻结</span>);
          case 3:
            return (span = <span style={{ color: "red" }}>删除</span>);
          default:
            return <div>{span}</div>;
        }
      },
    },
    {
      title: "操作",
      key: "action",
      render: (text, record) => (
        <Space size="middle">
          <Button
            size="small"
            style={{ color: "green" }}
            onClick={() => reding(record.id)}
          >
            查看
          </Button>

          <Popconfirm
            title="确定删除啊这条数据吗?"
            onConfirm={()=>confirm(record.id)}
            okText="删除"
            cancelText="取消"
          >
            <Button
              size="small"
              style={{ color: "red" }}
            >
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  const data = [
    {
      key: "1",
      name: "John Brown",
      age: 32,
      address: "New York No. 1 Lake Park",
      tags: ["nice", "developer"],
    },
    {
      key: "2",
      name: "Jim Green",
      age: 42,
      address: "London No. 1 Lake Park",
      tags: ["loser"],
    },
    {
      key: "3",
      name: "Joe Black",
      age: 32,
      address: "Sidney No. 1 Lake Park",
      tags: ["cool", "teacher"],
    },
  ];

  //添加key
  const addkey = (data) => {
    let i = 1;
    return data.filter((item) => (item.key = i++));
  };

  const brnData = [
    { id: "1", btnName: "群发短信" },
    { id: "2", btnName: "群发站内信" },
    { id: "3", btnName: "APP推送" },
    { id: "4", btnName: "赠送优惠券 " },
    { id: "5", btnName: "导出数据" },
  ];

  const headerData = [
    {
      id: 1,
      src: user,
      title: "全部注册用户",
      data: "399",
      cont: 1999,
    },
    {
      id: 2,
      src: money,
      title: "注册未申请",
      data: "399",
      cont: 1999,
    },
    {
      id: 3,
      src: foot,
      title: "注册已申请",
      data: "399",
      cont: 1999,
    },
  ];

  //表格请求
  useEffect(() => {
    resExcel();
  }, []);

  //请求数据列表
  const resExcel = (params) => {
    axios({
      method: "GET",
      url: "/system/usermanagement/userlist/shaixuanchaxun",
      params: {
        page: 1,
        limits: 999,
      },
    })
      .then((res) => {
        const excdata = addkey(res.data.data);
        //console.log(excdata)
        setexcelData(excdata);
      })
      .catch((err) => {
        console.log(err);
      });
    //注册未申请数
    axios({
      method: "GET",
      url: "/system/usermanagement/userlist/zhuceweishenqingshu",
      params: {},
    })
      .then((res) => {
        headerData[1].data = res.data.data;
        headerData[1].cont = res.data.count;
        setHeaddata(headerData);
      })
      .catch((err) => {
        console.log(err);
      });

    //注册已申请数
    axios({
      method: "GET",
      url: "/system/usermanagement/userlist/zhuceyishenqingshu",
      params: {},
    })
      .then((res) => {
        headerData[2].data = res.data.data;
        headerData[2].cont = res.data.count;
        setHeaddata(headerData);
      })
      .catch((err) => {
        console.log(err);
      });
  };

  //搜索
  const onFinish = (values) => {
    console.log("Success:", values);
    //返回时间格式
    let timerStart = "";
    let timerEnd = "";
    if (values.data) {
      timerStart = moment(values.data[0]._d).format("YYYY-MM-DD HH:mm:ss");
      timerEnd = moment(values.data[1]._d).format("YYYY-MM-DD HH:mm:ss");
      console.log("开始时间", timerStart);
    }
    const params = {
      account: values.user || "",
      end_time: timerEnd || "",
      start_time: timerStart || "",
      nickname: values.userqq || "",
      page: 1,
      limits: 10,
    };
    console.log("Success:", params);
    axios({
      method: "GET",
      url: "/system/usermanagement/userlist/shaixuanchaxun",
      params,
    })
      .then((res) => {
        console.log("搜索返回", res.data.data);
        const excdata = addkey(res.data.data);
        setexcelData(excdata);
      })
      .catch((err) => {
        console.log(err);
      });
  };

  //删除
  function confirm(e) {
    const deletdata =excelData.filter((item) =>{
      if(item.id != e){
      return item
    }})
    setexcelData(deletdata)
    message.success('删除成功');
  }
  

  //输入框内容
  const changeData = (e) => {
    //input输入什么，就监听这个方法，然后再修改state，然后返回到视图
    setsetSMScontent(e.target.value);
  };
  //标题输入框
  const changeTitle = (e) => {
    //input输入什么，就监听这个方法，然后再修改state，然后返回到视图
    setInvalTitle(e.target.value);
  };

  //选择框
  const onSelectChange = (selectedRowKeys) => {
    console.log("selectedRowKeys changed: ", selectedRowKeys);
    setState({ selectedRowKeys });
  };

  //reding查看数据列表
  let tabHead = [
    {
      id: 1,
      link: "/userDetails",
      name: "用户详情",
    },
    {
      id: 2,
      link: "/loginLog",
      name: "登录日志",
    },
  ];
  let routes = [
    {
      path: "/userDetails",
      component: userDetails,
    },
    {
      path: "/loginLog",
      component: loginLog,
    },
  ];
  const [tabdata, setstate] = useState(1);
  const reding = (id) => {
    //用户详情
    // axios({
    //   method: "GET",
    //   url: "/system/usermanagement/userlist/yonghuxiangqing",
    //   params: {
    //     id: 1,
    //   },
    // })
    //   .then((res) => {
    //     console.log(res)
    //     // sessionStorage.setItem("userDetails",JSON.stringify({ LoginList, excdata }));
    //     setTimeout(setIsModalList(true),500)
    //   })
    //   .catch((err) => {
    //     console.log(err);
    //   });
    //登录日志
    axios({
      method: "GET",
      url: "/system/usermanagement/userlist/denglurizhi",
      params: {
        id: id,
        page: 1,
        limits: 999,
      },
    })
      .then((res) => {
        const excdata = addkey(res.data.data);
        //登录日志
        sessionStorage.setItem("LoginLog", JSON.stringify(excdata));
        setTimeout(setIsModalList(true), 500);
      })
      .catch((err) => {
        console.log(err);
      });
  };

  const { selectedRowKeys } = state;
  const rowSelection = {
    selectedRowKeys,
    onChange: onSelectChange,
  };
  const hasSelected = selectedRowKeys.length > 0;

  //弹窗点击
  const showModal = (event) => {
    switch (event) {
      case "1":
        return setIsModalVisible(true);
      case "2":
        return setIsModalGroup(true);
      case "4":
        couponList();
        return setIsModalCoupon(true);
      default:
    }
    console.log("点击了");
  };
  const handleOk = (event) => {
    //提交清空
    console.log("勾选内容", selectedRowKeys);
    switch (event) {
      case "1":
        setsetSMScontent();
        setIsModalVisible(false);
        return;
      case "2":
        setsetSMScontent();
        setInvalTitle();
        setIsModalGroup(false);
        return;
      case "4":
        setInvalTitle();
        setIsModalCoupon(false);
        return;
      case "5":
        setIsModalCoupon(false);
        return;
      default:
    }
  };

  const handleCancel = () => {
    setIsModalGroup(false);
    setIsModalVisible(false);
    setIsModalCoupon(false);
    setIsModalList(false);
  };
  //搜索优惠券
  const selectCoupon = () => {
    console.log("搜索", invalTitle);
  };
  //优惠券列表
  const couponList = () => {
    console.log("youhui");
    //优惠券列表
    axios({
      method: "GET",
      url: "/system/usermanagement/userlist/youhuijuan",
      param:1,
    })
      .then((res) => {
        console.log(res);
      })
      .catch((err) => {
        console.log(err);
      });
  };

  return (
    <div>
      <div className="list-box">
        {headdata.map((item) => (
          <div className="userList-box" key={item.id}>
            <div className="uer-titel">
              <div className="icon-img">
                <Image className="icon-img" src={item.src} alt="用户" />
              </div>
              <p className="big-txt">{item.title}</p>
              <span className="small-txt">
                <p className="moth">本月/</p>
                <p className="year">今年</p>
              </span>
            </div>
            <div>
              <span className="bigtitle">{item.data}/</span>
              <span className="smalltitle">{item.cont}</span>
            </div>
            <div>
              <span className="describe">+45% 同比增长</span>
            </div>
          </div>
        ))}
      </div>
      <TitelSmall type="筛选查询"></TitelSmall>
      <div className="50">
        <Form onFinish={onFinish} className="select-box">
          <Form.Item label="用户账号" name="user" style={{ width: "250px" }}>
            <Input allowClear></Input>
          </Form.Item>
          <Form.Item label="用户昵称" name="userqq" style={{ width: "250px" }}>
            <Input allowClear></Input>
          </Form.Item>
          <Form.Item label="注册时间" name="data" style={{ width: "280px" }}>
            <RangePicker />
          </Form.Item>
          <Form.Item>
            <Button
              htmlType="submit"
              style={{
                width: "120px",
              }}
              className="login-form-button"
            >
              搜索
            </Button>
          </Form.Item>
        </Form>
      </div>
      <TitelSmall type="数据列表"></TitelSmall>
      <div style={{ marginBottom: 16 }} className="buton-box">
        <div style={{ marginLeft: 8 }}>
          <span>
            {hasSelected
              ? `当前选中 ${selectedRowKeys.length} 条数据`
              : "暂未选中"}
          </span>
        </div>
        <div className="btn-group">
          {brnData.map((item) => (
            <Button
              className="btn-ev"
              key={item.id}
              type="primary"
              onClick={() => showModal(item.id)}
              disabled={!hasSelected}
            >
              {item.btnName}
            </Button>
          ))}
        </div>
      </div>
      <Table
        rowSelection={rowSelection}
        columns={columns}
        dataSource={excelData}
      />
      {/* 短信弹窗 */}
      <Modal
        title="群发短信"
        visible={isModalVisible}
        onOk={() => handleOk("1")}
        onCancel={handleCancel}
      >
        <div className="usersum">
          发送对象:&nbsp;&nbsp;&nbsp;&nbsp;共
          <p style={{ color: "red" }}>{selectedRowKeys.length}</p>个用户
        </div>
        短信内容：
        <TextArea
          maxLength="500"
          value={inval}
          rows={4}
          onChange={(e) => changeData(e)}
        />
        <p>
          发送时系统会自动在结尾追加【**金服】，请勿重复添加。
          内容上限不能超过500字，当前已输入3字，将作为1条发送
        </p>
        <div className="send-title">
          <div style={{ display: "flex" }}>
            发送条数：<p style={{ color: "red" }}>{selectedRowKeys.length}</p>条
          </div>
          <p>可用短信条数：100000条 </p>
        </div>
      </Modal>
      {/* 群发站内内容 */}
      <Modal
        title="群发站内内容"
        visible={isModalGroup}
        onOk={() => handleOk("2")}
        onCancel={handleCancel}
      >
        <div className="usersum">
          发送对象:&nbsp;&nbsp;&nbsp;&nbsp;共
          <p style={{ color: "red" }}>{selectedRowKeys.length}</p>个用户
        </div>
        标题
        <Input
          maxLength="20"
          value={invalTitle}
          onChange={(e) => changeTitle(e)}
        />
        内容：
        <TextArea
          maxLength="100"
          value={inval}
          rows={4}
          onChange={(e) => changeData(e)}
        />
        <p>站内信标题不能超过20个字，内容不能超过100个字。</p>
      </Modal>
      {/* 赠送优惠券 */}
      <Modal
        title="赠送优惠券"
        visible={isModalCoupon}
        onOk={() => handleOk("4")}
        onCancel={handleCancel}
        width={1000}
      >
        <div>
          <Input
            style={{ width: "220px" }}
            maxLength="20"
            value={invalTitle}
            placeholder="优惠券名称/优惠券编号"
            onChange={(e) => changeTitle(e)}
          />
          <Button
            type="primary"
            icon={<SearchOutlined />}
            onClick={selectCoupon}
          ></Button>
          <Table
            rowSelection={rowSelection}
            columns={columns}
            dataSource={data}
          />
        </div>
      </Modal>
      {/* 查看列表 */}
      <Modal
        title="查看列表"
        visible={isModalList}
        onOk={() => handleOk("5")}
        onCancel={handleCancel}
        width={1000}
        footer={null}
      >
        <div className="red">
          <Router>
            <div>
              <ul className="red-tab">
                {tabHead.map((item) => {
                  return (
                    <Button
                      type={tabdata == item.id ? "primary" : ""}
                      className="red-tab-item"
                      key={item.link}
                      onClick={() => setstate(item.id)}
                    >
                      <Link to={item.link}>{item.name}</Link>
                    </Button>
                  );
                })}
              </ul>
            </div>
            <Switch>
              {routes.map((item) => {
                return (
                  <Route
                    path={item.path}
                    component={item.component}
                    key={item.path}
                  ></Route>
                );
              })}
              <Redirect to="/userDetails" />
            </Switch>
          </Router>
        </div>
      </Modal>
    </div>
  );
}
function userDetails() {
  return <div>用户列表</div>;
}

function loginLog() {
  const LoginList = [
    {
      title: "时间",
      dataIndex: "time",
      key: "time",
      render: (text, record) => {
        let span = record.time;
        let timer = span.split("T");
        let datatime = timer[1].split(".");
        return (
          <div>
            {timer[0]}&nbsp;&nbsp;{datatime[0]}
          </div>
        );
      },
    },
    {
      title: "IP",
      dataIndex: "ip",
      key: "ip",
    },
    {
      title: "地区",
      dataIndex: "address",
      key: "address",
    },
    {
      title: "登录方式",
      dataIndex: "loginMode",
      key: "loginMode",
    },
  ];
  const list = JSON.parse(sessionStorage.getItem("LoginLog"));
  console.log(list);
  return (
    <div>
      <Table columns={LoginList} dataSource={list} />
    </div>
  );
}
